package com.ymttest.database.sharding;

import io.shardingjdbc.core.api.algorithm.sharding.ListShardingValue;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import com.ymt.core.tool.Logger;

/**
 * Created by zhangyifan on 2017/12/4.
 */
public class ComplexKeysDatabaseAlgorithm extends ComplexKeysAlgorithm {

	@Override
	public Collection<String> doInSharding(
			final Collection<String> availableTargetNames,
			final ListShardingValue<Long> shardingValues) {
		List<String> result = new ArrayList<String>();

		if (availableTargetNames.size() == 1) {
			String targetName = availableTargetNames.iterator().next();
			shardingValues.getValues().forEach(v -> result.add(targetName));
			return result;
		}

		//123456789 --%10000--> 6789 --/100--> 67 --%8--> 3 --+1--> db_4
		for (Long value : shardingValues.getValues()) {
			boolean hit = false;
			long index = (value % 10000 / 100) % availableTargetNames.size()
					+ 1;
			for (String each : availableTargetNames) {
				if (each.endsWith("_" + index)) {
					result.add(each);
					hit = true;
					break;
				}
			}
			if (!hit) {
				throw new RuntimeException(
						"No target db found for shardingValue:" + value);
			}
		}
		Logger.info(String.format("数据库为: %s", result));
		return result;
	}
}
